package com.fumihiko.modules.ca.controller;

import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fumihiko.common.exception.BusinessException;
import com.fumihiko.common.utils.*;
import com.fumihiko.modules.ca.bean.GetTokenBean;
import com.fumihiko.modules.ca.bean.VerifyTokenBean;
import com.fumihiko.modules.ca.service.UserTokenService;
import com.fumihiko.modules.ca.vo.UserTokenVo;
import com.fumihiko.modules.sys.service.SysDictService;
import com.fumihiko.modules.wsbj.entity.UpProBasicProcessEntity;
import com.fumihiko.modules.wsbj.service.TbTokenService;
import com.fumihiko.modules.wsbj.service.UpProBasicService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


@RestController
@RequestMapping("/token")
@Api(value = "UserSignController", tags = {"授权验证接口"})
public class UserSignController {

    @Autowired
    private TbTokenService tbTokenService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private UpProBasicService upProBasicService;

    @Value("${redirectUrl}")
    private String redirectUrl;

    @Value("${redirectUrlOut}")
    private String redirectUrlOut;

    @Value("${descrypt}")
    private String descrypt;

    @Value("${redirectUrlError}")
    private String redirectUrlError;

    @Value("${appId}")
    private String appId;

    @Value("${appSecret}")
    private String appSecret;

    @Value("${timestamp}")
    private String timestamp;

    @Value("${userUrl}")
    private String userUrl;

////    @CrossOrigin
//    @PostMapping("getToken")
//    @ApiOperation(value = "获取TOKEN接口", notes = "获取TOKEN接口")
//    public void getToken(@RequestBody(required = false) GetTokenBean request, HttpServletResponse resp)  throws Exception{
//        JSONObject jSONObject = new JSONObject();
//        try {
////            String s = "2021-11-21 11:09:10";
////            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////
////            Date date = simpleDateFormat.parse(s);
////
////            long time = date.getTime();
////            String res = String.valueOf(time);
//
//            String appId = request.getAppId();
//            String appSecret = request.getAppSecret();
//            String timestamp = request.getTimestamp();
//            String sign = request.getSign();
//
//            String accessToken = userTokenService.getToken(appId, appSecret,timestamp, sign);
//            Cookie cookie = new Cookie("token",accessToken);
//            cookie.setPath("/");
//            //cookie.setDomain("39.98.148.165");
////        cookie.setHttpOnly(true);
//            resp.addCookie(cookie);
//
//
//            //resp.sendRedirect(redirectUrl);
//            resp.sendRedirect(redirectUrl);
//
//        }catch (BusinessException be){
//            be.printStackTrace();
//        }
//
//    }

//    @PostMapping("verifyToken")
//    @ApiOperation(value = "验证TOKEN接口", notes = "验证TOKEN接口")
//    public String verifyToken(@RequestBody(required = false) VerifyTokenBean request, @RequestHeader String accessToken, HttpServletResponse response)  throws Exception{
//        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        //HttpServletResponse response = servletRequestAttributes.getResponse();
//        //HttpServletRequest request1 = servletRequestAttributes.getRequest();
//        JSONObject jSONObject = new JSONObject();
//        try {
//            String areaCode = request.getAreaCode();
//            if(null == accessToken || "".equals(accessToken)){
//                jSONObject.put("code", SxConstants.SERVER_PARM_IS_NULL);
//                jSONObject.put("msg", "存在必填参数为空accessToken");
//                return jSONObject.toJSONString();
//            }
//            if(null == areaCode || "".equals(areaCode)){
//                jSONObject.put("code", SxConstants.SERVER_PARM_IS_NULL);
//                jSONObject.put("msg", "存在必填参数为空areaCode");
//                return jSONObject.toJSONString();
//            }
//            UserTokenVo userTokenVo = userTokenService.getUserTokenVoObjByAccessToken(accessToken);
//            if(null== userTokenVo){
//                Cookie cookie = new Cookie("token",null);
//                cookie.setMaxAge(0); //设置立即删除
//                response.addCookie(cookie);
//
//                jSONObject.put("code", SxConstants.SERVER_ACCESSTOKEN_ERROR_CODE);
//                jSONObject.put("msg", "accessToken错误");
//                return jSONObject.toJSONString();
//            }
//            Long sec = DateTimeUtil.getTimeMinusToSec(DateTimeUtil.getCurrentTime(), userTokenVo.getExpirationTime());
//
//
//            if(sec > 0){
//                Cookie cookie = new Cookie("token",null);
//                cookie.setMaxAge(0); //设置立即删除
//                response.addCookie(cookie);
//
//                jSONObject.put("code", SxConstants.SERVER_ACCESSTOKEN_EXP_CODE);
//                jSONObject.put("msg", "accessToken过期");
//                return jSONObject.toJSONString();
//            }
//
//            //userTokenService.updateUserTokenVoAreaCode(areaCode, accessToken);
//
//            Cookie cookie = new Cookie("token",accessToken);
//            System.out.println(response.getContentType());
//            cookie.setPath("/");
//            response.addCookie(cookie);
//
//            JSONObject jSONObject11 = new JSONObject();
//            jSONObject.put("code", SxConstants.SERVER_SUCESS_CODE);
//            jSONObject.put("msg", "鉴权成功");
//
//            jSONObject11.put("url", "http://39.98.148.165/lljk-admin-vue/#/home");
//            jSONObject.put("data",jSONObject11);
//            return jSONObject.toJSONString();
//           // return "redirect:http://localhost:8001/#/home";
//
//        }catch (BusinessException be){
//            jSONObject.put("code", SxConstants.SERVER_ERROR_CODE);
//            jSONObject.put("msg", be.getMsg());
//            return jSONObject.toJSONString();
//        }
//
//    }

    @GetMapping("verifyToken")
    public void verifyToken(HttpServletRequest req, HttpServletResponse resp,String accessToken)  throws Exception{

        try {


//            File file = new File("fumihiko-admin\\src\\main\\resources\\static\\swagger\\sh_pub.cer");
//            System.out.println(file.getCanonicalPath());
//
//            System.out.println(file.getAbsolutePath());
//
//           String value = RSAUtil.getStrPublicKey(file.getAbsolutePath());
//           //String value2 = RSAUtil.encryptByPublicKey(value,"220283198902254237");
//           String value3 = RSAUtil.descryptByPublicKey(value,certNo);
//            System.out.println(value3);
            //http://ggfw.mzj.beijing.gov.cn/uip/bjt/getUseInfo?client_id=2000&clientSecret=c8c9b028adbb49a04d40292f89b&access_token=dd3068af-3fab-3d19-bf3a-ead6cedf502b
            if(accessToken == null || accessToken.equals(""))
            {
                resp.sendRedirect(redirectUrlError);
            }else
            {
                String key = descrypt;
                //解密access_token
                accessToken=accessToken.trim();
                accessToken= accessToken.replaceAll(" ","+");
                String token = RSAUtil.descryptByPublicKeyFen(key,accessToken);

                //获取用户信息接口
                String idcardValue = formData(token,resp);

                //解密身份证
                idcardValue = idcardValue.trim();
                idcardValue = idcardValue.replaceAll(" ","+");
                String idCardNo = RSAUtil.descryptByPublicKeyFen(key,idcardValue);
                if(idCardNo == null || idCardNo.equals(""))
                {
                    resp.sendRedirect(redirectUrlError);
                }else
                {
                    String access_Token = tbTokenService.getToken(appId, appSecret,timestamp);
                    Cookie cookie11 = new Cookie("idcard",idCardNo);
                    Cookie cookie = new Cookie("token",access_Token);

                    cookie.setPath("/");
                    cookie11.setPath("/");
//                cookie.setDomain("39.98.148.165");
//        cookie.setHttpOnly(true);
                    resp.addCookie(cookie);
                    resp.addCookie(cookie11);

                    //resp.sendRedirect(redirectUrl);
                    resp.sendRedirect(redirectUrl);
                }

            }

        }catch (BusinessException be){

            be.printStackTrace();
        }


    }


    public String formData( String token,HttpServletResponse resp) throws IOException {

        //获取token
        String url = userUrl+token;
        StringBuffer buffer = new StringBuffer();
        String jsonString = "";
        String certNo = "";
        try {
            URL url2 = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url2.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            InputStream inputStream = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();

            inputStream.close();
            inputStream = null;
            httpURLConnection.disconnect();
            str = buffer.toString();
            //int index = str.indexOf("(");
            //jsonString = str.substring(index + 1, str.length() - 1);

            JSONObject myJson = JSONObject.parseObject(str.toString());
            String coderesult = myJson.getString("meta");

            String result = myJson.getString("data");
            if(result == null || result.equals(""))
            {
                return certNo;
            }else
            {
                JSONObject resultJson = JSONObject.parseObject(result);
                certNo = resultJson.getString("certNo");
            }
//            if ("0".equals(code)) {
//
//                String result = myJson.getString("data");
//                JSONObject resultJson = JSONObject.parseObject(result);
//                certNo = resultJson.getString("certNo");
//
//            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return certNo;
    }


    /**
     * 列表
     */
    @RequestMapping("/list")

    public R list(@RequestParam Map<String, Object> params){
        //PageUtils page = upProBasicService.queryPage(params);
        String idCards = (String)params.get("key");
        QueryWrapper<UpProBasicProcessEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("b.APPLYER_CARDCODE",idCards);
        int pageNo = Integer.valueOf((String)params.get("page"));

        int pageSize = Integer.valueOf((String)params.get("limit"));

        Page<UpProBasicProcessEntity> page = new Page<>(pageNo,pageSize);
        IPage<UpProBasicProcessEntity> pageList =  upProBasicService.selectBasicPage(page,queryWrapper);
        return R.ok().put("page", new PageUtils(pageList));
    }


}
